//
//  NSString+CLUtility.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2017/1/7.
//  Copyright © 2021年 梁慧聪. All rights reserved.
//

static NSString * const kURLRegEx = @"((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";

#import "NSString+CLUtility.h"
#import <YYKit/NSArray+YYAdd.h>
#import "NSString+CLUtility.h"
#import "NSDictionary+CLCategory.h"
@implementation NSString (CLUtility)

- (BOOL)isValidURL{
    NSPredicate *urlPredic = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",kURLRegEx];
    return [urlPredic evaluateWithObject:self];
}

- (BOOL)isLocal{
    NSURL *url = [NSURL URLWithString:self];
    return [url.host.lowercaseString isEqualToString:@"localhost"] || [url.host isEqualToString:@"127.0.0.1"];
}

- (BOOL)isHTTPProtocol{
    return [self hasPrefix:@"http"] || [self hasPrefix:@"https"];
}

- (NSString *)ellipsizeWithMaxLength:(NSInteger)maxLength{
    if (maxLength >= 2 && self.length > maxLength) {
        NSInteger index1 = (maxLength + 1) / 2;
        NSInteger index2 = self.length - maxLength / 2;
        
        NSString *index1Str = [self substringToIndex:index1];
        NSString *index2Str = [self substringFromIndex:index2];
        
        return [NSString stringWithFormat:@"%@…\u2060%@",index1Str,index2Str];
    }
    return self;
}

- (NSDictionary *)getWebViewJSONDicWithPrefix:(NSString *)prefix{
    NSDictionary *jsonDic = nil;
    if ([self hasPrefix:prefix]) {
        NSString *jsonStr = [self substringFromIndex:prefix.length];
        
        jsonStr = [jsonStr stringByRemovingPercentEncoding];
        if (jsonStr) {
            jsonDic = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:NULL];
            if (jsonDic && [jsonDic isKindOfClass:[NSDictionary class]]) {
                return jsonDic;
            }
        }
    }
    return jsonDic;
}

- (NSString*)cl_URLEncodedString {
    return [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
}

- (NSString*)cl_URLDecodedString {
    return [self stringByRemovingPercentEncoding];
}

- (NSString *)cl_subStringFromRange:(NSRange)stringRange {
    NSString *string = self;
    if ((int)(stringRange.location) <0 || (int)(stringRange.length) <= 0) return nil;
    NSRange originRange = NSMakeRange(0, string.length);
    if (stringRange.length > 0 && stringRange.location >= originRange.location && NSMaxRange(stringRange) <= NSMaxRange(originRange)) {
        return [string substringWithRange:stringRange];
    }
    return string;
}

- (NSString *)cl_substringFromIndex:(NSInteger)from {
    return [self cl_subStringFromRange:NSMakeRange(from + 1, self.length - from - 1)];
}

- (NSString *)cl_substringToIndex:(NSInteger)to {
    return [self cl_subStringFromRange:NSMakeRange(0, to + 1)];
}

- (NSString *)cl_urlSafeAppendParams:(NSDictionary *)paramDicts {
    NSString *url = self;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if (!NULLString(url)) {
        [dict addEntriesFromDictionary:paramDicts];
        if ([url containsString:@"?"]) {
            NSArray *tmp = [url componentsSeparatedByString:@"?"];
            NSString *query = [tmp objectOrNilAtIndex:1];
            if (!NULLString(query)) {
                NSString * propertys = query;
                NSArray *subArray = [propertys componentsSeparatedByString:@"&"];
                for (NSString * params in subArray) {
                    NSRange range = [params rangeOfString:@"="];
                    if (range.location != NSNotFound) {
                        NSString * paramValue = [params cl_substringFromIndex:(int)(range.location+1)];
                        NSString * paramName = [params cl_substringToIndex:(int)(range.location)];
                        [dict cl_setObjectSafe:paramValue forKey:paramName];
                    }
                }
            }
        }
    }
    if (dict.count) {
        NSString *host = [url componentsSeparatedByString:@"?"].firstObject;
        NSMutableArray *pArray = [NSMutableArray array];
        for (NSString *key in dict) {
            [pArray addObject:[NSString stringWithFormat:@"%@=%@",key,[dict cl_stringForKey:key]]];
        }
        url = [NSString stringWithFormat:@"%@?%@",host,[pArray componentsJoinedByString:@"&"].cl_URLEncodedString];
    }
    return url;
}

//获取当前时间戳字符串 10位
+ (NSString *)getTimestampSince1970 {
    NSDate *datenow = [NSDate date];//现在时间
    int64_t interval = [datenow timeIntervalSince1970] * 1000;//13位的*1000
    NSString *timeSp = [NSString stringWithFormat:@"%lld",interval];
    return timeSp;
}

/// 正则搜索相关字符位置
- (NSArray <NSTextCheckingResult*>*)matchesByPattern:(NSString *)pattern {
    if (NULLString(self)) {return @[];}
    @try {
        NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
        return [regularExpression matchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length)];
    } @catch (NSException *exception) {return @[];}
    return @[];
}

/// 正则替换字符
- (NSString *)replacingCharacters:(NSString *)pattern withString:(NSString *)template {
    @try {
        NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
        
        return [regularExpression stringByReplacingMatchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length) withTemplate:template];
//        return regularExpression.stringByReplacingMatches(in: self, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, length), withTemplate: template)
        
    } @catch (NSException *exception) {return self;}
    return self;
}

- (BOOL)isEmpty {
    return NULLString(self);
}

- (NSString *)removeSEHeadAndTail {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (NSString *)removeEnterAll {
    return [[self stringByReplacingOccurrencesOfString:@"\r" withString:@""] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
}
@end
